package web;

import domain.Student;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import model.Database;
import model.EltcException;
import model.Model;
import model.ModelImpl;

public class Navigator {

    String pageTo;
    String userPath;
    // Database db = Database.getInstance();
    HttpServletRequest request;
    Model model;

    public Navigator(String userPath, HttpServletRequest request) {
        model = new ModelImpl();
        this.userPath = userPath;
        this.request = request;
        createPageTo();
    }

    public String getPageTo() {
        return pageTo;
    }

    private void createPageTo() {
        try {
            if (userPath == null) {
                userPath = "";
            }

            if (userPath.equals("/index")) {
                pageTo = "/index.jsp";;
            } else if (userPath.equals("/showStudents")) {
                addToRequestStudents(request);

                pageTo = "/WEB-INF/view/mainJsp.jsp";

            } else if (userPath.equals("/createStudent")) {

                pageTo = "/WEB-INF/view/studentEdit.jsp";

            } else if (userPath.equals("/editStudent")) {
                Student student = model.getObject(Integer.valueOf(request.getParameter("id")), Student.class);
                request.setAttribute("bean", student);
                pageTo = "/WEB-INF/view/studentEdit.jsp";

            } else if (userPath.equals("/deleteStudent")) {

                int id = Integer.parseInt(request.getParameter("id"));
                try {
                    model.removeObject(model.getObject(id, Student.class));
                } catch (Exception ex) {
                    request.setAttribute("exception", new EltcException("Удаление не произошло, объект используется в другой таблице", ex));
                }
                addToRequestStudents(request);
                pageTo = "/WEB-INF/view/mainJsp.jsp";

            } else {

                pageTo = "/errorpage.jsp";
            }
        } catch (Exception ex) {
            Logger.getLogger(Navigator.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void addToRequestStudents(HttpServletRequest request) throws EltcException {
        List<Student> students = model.getObjects(Student.class);
        request.setAttribute("students", students);
    }
}
